#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# zhouyi 6098550@qq.com

import threading
import mi_machine
import mi_config

config         = mi_config.MiConfig()
config.Load('./config.json')
config.Show()
machine_client = mi_machine.MiMachineClient(config.machine_config)
lock = threading.Lock()

def StartWork():
    lock.acquire()
    machine_client.Write(mi_machine.START_WORK, 2)
    lock.release()
    return '{"code":1}'

def StopWork():
    lock.acquire()
    machine_client.Write(mi_machine.STOP_WORK, 2)
    lock.release()
    return '{"code":1}'

def AbortWork():
    lock.acquire()
    machine_client.Write(mi_machine.ABORT_WORK, 2)
    lock.release()
    return '{"code":1}'

def WorkStatus():
    lock.acquire()
    status = machine_client.Read(mi_machine.WORK_STATUS)
    lock.release()
    return '{"status":%d}'%status

def GetWeight(no):
    lock.acquire()
    if no>0 and no<=3:
        weight = machine_client.Read(mi_machine.BASE_WEIGHT+no)
        lock.release()
        return '{"no":%d, "weight":%d}'%(no, weight)

    lock.release()
    return '{"no":%d, "msg":"the no param is error!"}' % no